//
//  KAVerCodeVC.swift
//  kano
//
//  Created by Frank on 2024/10/30.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa

class KAVerCodeVC: KABaseVC {
    
    private let disposeBag = DisposeBag()

    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = UIColor.white
        var_cornerView.layer.cornerRadius = kscale(30)
        var_cornerView.layer.masksToBounds = true
        var_cornerView.frame = CGRectMake(kscale(20), UIDevice.ka_fullNavHeight+kscale(40), var_screenWidth-kscale(40), kscale(330))
        return var_cornerView
    }()
    
    lazy var var_titleLabel: UILabel = {
        let var_titleLabel = UILabel()
        var_titleLabel.x = kscale(20)
        var_titleLabel.y = kscale(32)
        var_titleLabel.width = var_cornerView.width-kscale(40)
        var_titleLabel.height = kscale(32)
        var_titleLabel.textAlignment = .left
        var_titleLabel.font = UIFont.systemFont(ofSize: kscale(20), weight: .bold)
        var_titleLabel.textColor = .black
        var_titleLabel.text = "Send SMS Verification Code to"//"Recover Password"
        var_titleLabel.sizeToFit()
        var_titleLabel.numberOfLines = 0
        return var_titleLabel
    }()
    
//    lazy var var_subTitleLabel: UILabel = {
//        let var_subTitleLabel = UILabel()
//        var_subTitleLabel.frame = CGRectMake(kscale(20), var_titleLabel.bottom+kscale(12), var_cornerView.width-kscale(40), kscale(32))
//        var_subTitleLabel.textAlignment = .left
//        var_subTitleLabel.font = UIFont.systemFont(ofSize: kscale(16), weight: .regular)
//        var_subTitleLabel.textColor = .black
//        var_subTitleLabel.text = "Send SMS Verification Code to"
//        return var_subTitleLabel
//    }()
    
    lazy var var_mobileLabel: UILabel = {
        let var_mobileLabel = UILabel()
        var_mobileLabel.frame = CGRectMake(kscale(20), var_titleLabel.bottom+kscale(12), var_cornerView.width-kscale(40), kscale(32))
        var_mobileLabel.font = UIFont.systemFont(ofSize: kscale(16), weight: .regular)
        var_mobileLabel.textColor = .black
        var_mobileLabel.text = "+234 " + KAUserManager.shared.user.notificationMessage
        return var_mobileLabel
    }()
    
    lazy var var_pwdView: KAVerCodeView = {
        var_pwdView = KAVerCodeView(placeHolder: "Please enter verification code")
        var_pwdView.x = kscale(20)
        var_pwdView.y = var_mobileLabel.bottom + kscale(20)
        var_pwdView.size = CGSizeMake(var_cornerView.width-kscale(40), kscale(48))
        var_pwdView.editDidEndHandle = { view, tfInfo in
            tfInfo.geographicalLongitude = "ForgotPassword_SMSCode"
            tfInfo.paginationId = "ForgotPassword_Process"
            KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
        }
        return var_pwdView
    }()
    
    private lazy var voiceCodeBtn: UIButton = {
        let voiceCodeBtn = UIButton()
//        voiceCodeBtn.backgroundColor = .colorf2f2f5
        voiceCodeBtn.setTitle("Voice code", for: .normal)
        voiceCodeBtn.setTitleColor(.themeColor, for: .normal)
        voiceCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        voiceCodeBtn.addTarget(self, action: #selector(voiceCodeBtnClick), for: .touchUpInside)
        voiceCodeBtn.isHidden = true
        return voiceCodeBtn
    }()
    
    private lazy var resendBtn: UIButton = {
        let resendBtn = UIButton()
        resendBtn.backgroundColor = .clear
        resendBtn.setTitle("Get Verification Code", for: .normal)
        resendBtn.setTitleColor(.themeColor, for: .normal)
        resendBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        resendBtn.addTarget(self, action: #selector(resendBtnClick), for: .touchUpInside)
        return resendBtn
    }()
    @objc func resendBtnClick() {
        if resendBtn.titleLabel?.text == "Get Verification Code" {
            let btnInfo = KABtnInfo(eleId: "creditProcess_status", pageId: "ForgotPassword_Process", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        }
        if resendBtn.titleLabel?.text == "Resend" {
            var eleId = currentCodeType == "0" ? "loanStay_process" : "creditCard_add"
            let btnInfo = KABtnInfo(eleId: eleId, pageId: "ForgotPassword_Process", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        }
        ka_checkMobile()
    }
    var firstVoiceClick: Bool = true
    @objc func voiceCodeBtnClick() {
        currentCodeType = currentCodeType == "0" ? "1" : "0"
        if resendBtn.titleLabel?.text == "Resend" {
            var eleId = currentCodeType == "0" ? "loanStay_process" : (firstVoiceClick ? "exitFlow_complete" : "creditCard_add")
            let btnInfo = KABtnInfo(eleId: eleId, pageId: "ForgotPassword_Process", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        }
        firstVoiceClick = false
        ka_checkMobile()
    }
    
    lazy var var_signBtn: UIButton = {
        let var_signBtn = UIButton(frame: CGRectMake(kscale(48), var_pwdView.bottom+kscale(48), var_cornerView.width-kscale(96), kscale(50.0)))
        var_signBtn.setTitle("Next Step", for: .normal)
        var_signBtn.setTitleColor(.white, for: .normal)
        var_signBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_signBtn.backgroundColor = .colorBDBDF5
        var_signBtn.layer.cornerRadius = kscale(25)
        var_signBtn.layer.masksToBounds = true
        var_signBtn.addTarget(self, action: #selector(ka_signButtonClick), for: .touchUpInside)
        return var_signBtn
    }()
    
    lazy var var_pictureView: KAPictureVerifyView = {
        let var_pictureView = KAPictureVerifyView { [self] code, captcheId in
            captchaId = captcheId
            captchaCode = code
            ka_sendCode()
//            ka_checkPicCode()
        }
        return var_pictureView
    }()
    

    //voice code / msg code
    var currentCodeType: String = "0"
    //picture code
    var captchaCode: String = ""
    private var captchaId: String = ""
    private var codeToken: String = ""
    private var verifyToken: String = ""
    
    //Timer
    private var count: Int = 60
    private var task: String?
}

extension KAVerCodeVC {
    func ka_checkPicCode() {
        NetService.ka_checkPictureCode(captchaId: captchaId, captchaCode: captchaCode) { isSuccess, message, response in
            if isSuccess {
                if response?.voucherQuantity?.operationalStatus == 0 {
                    self.var_pictureView.makeToast("Graphic verification code error")
                    self.var_pictureView.show()
                } else {
                    self.var_pictureView.dismiss()
                }
            } else {
                self.view.makeToast(message)
                self.var_pictureView.show()
            }
        }
    }
    func ka_checkMobile() {
        NetService.ka_checkMobileWith(mobile: KAUserManager.shared.user.notificationMessage) { [self] isSuccess, message, response in
            if isSuccess {
                guard let user = response?.voucherQuantity else { return }
                let defaultUser = KAUserManager.shared.user
                var newUser = defaultUser.merge(with: user)
                newUser.notificationMessage = KAUserManager.shared.user.notificationMessage
                KAUserManager.shared.user = newUser
                codeToken = user.authenticationToken
                ka_sendCode()
            } else {
                guard let status = response?.operationalStatus else { return }
                if ka_showPictureView(status) {
                    self.var_pictureView.show()
                    self.var_pictureView.makeToast(message)
                    return
                }
                self.view.makeToast(message)
                self.var_pictureView.dismiss()
            }
        }
    }
    private func ka_sendCode() {
        NetService.ka_sentCode(withType: currentCodeType, codeToken: codeToken, operationType: .forgetPwd, captchaCode: captchaCode) { [self] isSuccess, message, response in
            self.captchaId = ""
            self.captchaCode = ""
            if isSuccess {
                var eleId = currentCodeType == "0" ? "processCard_info" : "loanExit_status"
                let toastInfo = KAToastInfo(eleId: eleId, pageId: "ForgotPassword_Process", path: "\(KAVerCodeVC.self)")
                KAReport.ka_reportWith(type: .toast, data: toastInfo.kj.JSONObject())
                
                var toast = currentCodeType == "0" ? "\(var_smsToast) \(KAUserManager.shared.user.notificationMessage)." : var_voiceToast
                self.view.makeToast(toast)
                if response?.voucherQuantity != nil {
                    self.verifyToken = response!.voucherQuantity!.authenticationToken
                }
                startTimer()
                self.var_pictureView.dismiss()
            } else {
                guard let status = response?.operationalStatus else { return }
                if ka_showPictureView(status) {
                    self.var_pictureView.show()
                    self.var_pictureView.makeToast(message)
                    return
                }
                self.view.makeToast(message)
                self.var_pictureView.dismiss()
            }
        }
    }
    private func startTimer() {
        count = 60
        task = KATimer.execTask(self, selector: #selector(countdown), start: 0.0, interval: 1.0, repeats: true, async: false)
    }
    
    @objc private func countdown() {
        let button: UIButton = resendBtn
        
        if count > 0 {
            count -= 1
            button.isUserInteractionEnabled = false
            button.setTitleColor(.color8A8891, for: .normal)
            voiceCodeBtn.isHidden = true
            let string = "(" + "\(count)" + "s)"
            button.setTitle(string, for: .normal)
        } else {
            KATimer.cancelTask(task!)
            button.isUserInteractionEnabled = true
            button.setTitleColor(.themeColor, for: .normal)
            voiceCodeBtn.isHidden = false
            button.setTitle("Resend", for: .normal)
            var title = currentCodeType == "0" ? "Voice code" : "SMS code"
            voiceCodeBtn.setTitle(title, for: .normal)
        }
    }
}

extension KAVerCodeVC {
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_setUI()
        ka_bindUI()
        let data = KAPageInfo(eleId: "ForgotPassword_Process", path: "\(KAVerCodeVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
    }
    
    func ka_setUI() {
        view.backgroundColor = .colorf2f2f5
        ka_showCustomerNavBar(type: .normal)
        var_navBar.updateUI(alpha: 0)
        
        view.addSubview(var_cornerView)
        var_cornerView.addSubview(var_titleLabel)
//        var_cornerView.addSubview(var_subTitleLabel)
        var_cornerView.addSubview(var_mobileLabel)
        
        var_cornerView.addSubview(resendBtn)
        var_cornerView.addSubview(voiceCodeBtn)
        var_cornerView.addSubview(var_pwdView)
        
        var_cornerView.addSubview(var_signBtn)
        
        resendBtn.snp.makeConstraints { make in
            make.top.equalTo(var_pwdView.snp.bottom).offset(kscale(10))
            make.right.equalTo(var_pwdView)
        }
        voiceCodeBtn.snp.makeConstraints { make in
            make.top.equalTo(var_pwdView.snp.bottom).offset(kscale(10))
            make.left.equalTo(var_pwdView)
        }
    }
    
    func ka_bindUI() {
        var_pwdView.contentTF.rx.text
            .orEmpty
            .map { text in
                return (text.count == 6) ? .themeColor : .colorBDBDF5
            }
            .bind(to: var_signBtn.rx.backgroundColor)
            .disposed(by: disposeBag)

    }
    
    @objc func ka_signButtonClick() {
        guard var_pwdView.contentTF.text!.count == 6 else {
            view.makeToast("Please Enter 6-Digit Verification Code"); return
        }
        
        let btnInfo = KABtnInfo(eleId: "ForgotPassword_NextStep", pageId: "ForgotPassword_Process", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        
        let paramDic: [String: Any] = [
          "notificationMessage": KAUserManager.shared.user.notificationMessage,
          "validityStartTime": var_pwdView.contentTF.text!,
          "authenticationToken": codeToken,
          "processActionType": KAOperation.forgetPwd.rawValue,
          "smsCategory": 2,
          "softwareUpdateVersions": KAUserManager.shared.user.softwareUpdateVersions,
        ]
        view.showLoading()
        loginProvider.request(.changePwdVerCode(paramDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<Int>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else {
                                view.makeToast("Verification failure"); return
                            }
                            if content == 1 {
                                let vc = KANewPwdSetVC()
                                vc.codeToken = verifyToken  
                                navigationController?.pushViewController(vc, animated: true)
                                return
                            }
                            view.makeToast("Verification failure")
                        } else {
                            guard let status = response?.operationalStatus else { return }
                            if ka_showPictureView(status) {
                                self.var_pictureView.show()
                                self.var_pictureView.makeToast(message)
                                return
                            }
                            self.view.makeToast(message)
                            self.var_pictureView.dismiss()
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
}

